const { userSchema, shippingAddressSchema } = require("../../../db/model");
const express = require("express");
const uuid = require("../../../utils/uuid");
const { avatar } = require("../../../utils/default");
const { getToken, checkToken } = require("../../../utils/token");
const dayjs = require("dayjs");
const loginRouter = express.Router();

//登录并注册
loginRouter.post("/user/login", async (req, res) => {
  const { body } = req;
  const { phone, password } = body;
  try {
    if (phone && password) {
      const result = await userSchema.findOne({ phone });
      if (result) {
        if (result.password === password) {
          res.json({
            code: 200,
            msg: "登录成功",
            data: {
              result,
              token: getToken({ userId: result?._id, phone }),
            },
            succeed: true,
          });
          return;
        }
        res.json({
          code: 401,
          msg: "您输入的手机号或密码错误",
          data: { result, token: getToken({ userId: result?._id, phone }) },
          succeed: false,
        });
        return;
      }

      const results = await user_schema.create({
        _id: uuid,
        phone,
        avatar,
        userName: phone,
        password,
        email: "",
        birth: "",
        gender: "男",
        integral: 100,
        grade: "普通会员",
        createdItem: dayjs().unix(),
      });
      if (results) {
        res.json({
          code: 200,
          msg: "注册成功",
          data: { results, token: getToken({ userId: results?._id, phone }) },
          succeed: true,
        });
      }
      return;
    }
    res.json({
      code: 400,
      msg: "参数缺失",
      succeed: false,
    });
  } catch (error) {
    res.json({
      code: 500,
      msg: error,
      succeed: false,
    });
  }
});

module.exports = loginRouter;
